<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Business extends Backend
{

    /**
     * Business模型对象
     * @var \app\admin\model\Business
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
//        $this->model = new \app\admin\model\Business;
        $this->model = model('User');

    }
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter_Arr=json_decode($this->request->get('filter'),true);
            $op_Arr=json_decode($this->request->get('op'),true);
            $time="";
            if(!empty($filter_Arr['time'])){
                $time=$filter_Arr['time'];
            }
            unset($filter_Arr['time']);
            unset($op_Arr['time']);
            $this->request->get(['filter'=>json_encode($filter_Arr)]);
            $this->request->get(['op'=>json_encode($op_Arr)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $wherese['is_business']=1;
            $list = $this->model

                ->where($wherese)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)->each(function($item, $key)use($time){
                    if(!empty($time)){
                       $time_arr=explode(' - ',$time);
                        $start=strtotime($time_arr[0]);
                        $end=strtotime($time_arr[1]);
                        $where_m['createtime']=['between',[$start,$end]];
                    }
                    $where_m['user_id']=['in',$this->junior_ids($item['id'])];
                    $where_m['memo']=['in','管理员变更金额,充值钢豆'];
                    $money=db('user_money_log')->where($where_m)->sum('money');
                    $item['money']=$money;
                    return $item;
                });
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function junior_ids($pid)
    {
        $where['pid']=$pid;
        $list=db('user')->where($where)->field('id')->select();
        $ids=[];
        foreach($list as $k=>$v){
            $ids[]=$v['id'];
        }
        return $ids;
    }


}
